//
//  MineDetailViewController.m
//  Business Club
//
//  Created by 尹宁 on 16/4/15.
//  Copyright © 2016年 范琦. All rights reserved.
//

#import "MineDetailViewController.h"
#import "MineDetailTableViewCell.h"
#import "MineDetailModel.h"
#import "ChangeNickNameViewController.h"
#import "ChangePasswordViewController.h"

#import "ASIFormDataRequest.h"
#import "ASINetworkQueue.h"
#import "TZImagePickerController.h"

#import "MBProgressHUD.h"
static NSString *const reuseMineDetailTableViewCell = @"MineDetailTableViewCell";

@interface MineDetailViewController ()<UITableViewDelegate, UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,ASIHTTPRequestDelegate>
{
    NSString *token;
    NSMutableArray *arr;
}
@property (nonatomic, strong) UITableView *mineDeatilTableView;
@property (nonatomic, strong) NSMutableArray *listArr;
/**
 *  拍照
 */
@property (nonatomic, strong)  UIImagePickerController *imagePicker;
/**
 *  存放图片的数组
 */
@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, strong) ASINetworkQueue *queue;

// 存放图片string数组
@property (nonatomic, strong) NSMutableArray *strArr;
@property (nonatomic ,strong) NSString *ImageStr;

@property (nonatomic, strong) MBProgressHUD *mbView;// 视图加载
@end

@implementation MineDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"我的资料";
    self.view.backgroundColor = [UIColor huiseColor];
    token = [NSUSERDEFAULTS objectForKey:@"gettoken"];
    [self creatView];
//    [self getData];
    
    arr = [NSMutableArray array];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _mineDeatilTableView.frame = CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT);
}

- (void)getData
{
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:[NSString stringWithFormat:@"/My/myInfo.html?token=%@", token] RegisterApiMethod:RequestMethodGet];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dic = [request.responseBody objectForKey:@"result"];
        self.listArr = [NSMutableArray array];
        MineDetailModel *model = [[MineDetailModel alloc]init];
        model.nickname = [dic objectForKey:@"nickname"];
        model.company_name = [dic objectForKey:@"company_name"];
        model.avatar = [dic objectForKey:@"avatar"];
        model.sex = [dic objectForKey:@"sex"];
        model.name = [dic objectForKey:@"name"];
        
        [self.listArr addObject:model];
        [_mineDeatilTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        
    }];
    
}

- (void)creatView
{
    self.mineDeatilTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT) style:UITableViewStyleGrouped];
    
    _mineDeatilTableView.contentInset = UIEdgeInsetsMake(-22 * KSCREENWIDTH / 375, 0, 0, 0);
    [self.view addSubview:_mineDeatilTableView];
    self.mineDeatilTableView.delegate = self;
    self.mineDeatilTableView.dataSource = self;
//    self.mineDeatilTableView.rowHeight = KSCREENHEIGHT / 7;
    _mineDeatilTableView.sectionFooterHeight = 0;
    [_mineDeatilTableView registerNib:[UINib nibWithNibName:@"MineDetailTableViewCell" bundle:nil] forCellReuseIdentifier:reuseMineDetailTableViewCell];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseMineDetailTableViewCell];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];// 去掉点击之后的阴影
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    if (indexPath.section == 0) {
        MineDetailModel *model = self.listArr[0];
        if (indexPath.row == 0) {
        cell.nameLabel.text = @"头像";
        cell.headerImage.hidden = NO;
        [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:nil];
        } else  {
            cell.nameLabel.text = @"昵称";
            cell.labelText.text = model.nickname;
        }
    } else if (indexPath.section == 1) {
        MineDetailModel *model = self.listArr[0];
        cell.nameLabel.text = @"商户";
        cell.labelText.text = model.company_name;
        [cell setAccessoryType:UITableViewCellAccessoryNone]; // 不可点击时不显示右边箭头
    }
      else if (indexPath.section == 2) {
        MineDetailModel *model = self.listArr[0];
        cell.nameLabel.text = @"联系电话";
        cell.labelText.text = model.name;
        [cell setAccessoryType:UITableViewCellAccessoryNone]; // 不可点击时不显示右边箭头
      } else {
          cell.nameLabel.text = @"修改密码";
      }
    return cell;
}
- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; //设置image picker的来源,这里设置为摄像头
        _imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        _imagePicker.allowsEditing = YES; // 允许编辑
        _imagePicker.delegate = self; // 设置代理。检测操作
    }
    return _imagePicker;
    
}


//选择拍照还是从相册选择
- (void)takePhotoOrSelectAlbum
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    [sheet showInView:self.view];
    
}

#pragma mark -UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self presentViewController:self.imagePicker animated:YES completion:nil];
        }
            break;
        case 1:
        {
            // 打开相册
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
            imagePickerVc.maxImagesCount = 9 - self.imageArray.count;
            imagePickerVc.navigationBar.barTintColor = [UIColor redColor]; //相册选择器的导航栏的颜色
            imagePickerVc.oKButtonTitleColorDisabled = [UIColor redColor]; //选择照片时文字的颜色
            imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor]; //没有选择照片时文字的颜色
            imagePickerVc.allowPickingVideo = NO;
            // You can get the photos by block, the same as by delegate.
            // 你可以通过block或者代理，来得到用户选择的照片.
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets) {
                
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
            
        }
            break;
        default:
            break;
    }
}

#pragma mark - UIImagePickerController代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image;
    //如果允许编辑则获得编辑后的照片，否则获取原始照片
    if (self.imagePicker.allowsEditing) {
        image = [info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的图片
    }else{
        image = [info objectForKey:UIImagePickerControllerOriginalImage]; //获取原始照片
    }
    [self.imageArray addObject:image];
  
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    
    // 把选中的图片转成NSData类型(缩略图)
    for (UIImage *image in photos) {
        
        NSData *data = UIImageJPEGRepresentation(image, 1.0f);
        [arr addObject:data];
    }
    [self shangchuan];
    //
    //        // 把选中的图片转成NSData类型(全屏图)
    //    NSData *data1 = UIImageJPEGRepresentation([UIImage imageWithCGImage:[[[assets objectAtIndex:0] defaultRepresentation] fullScreenImage]], 0);    [self.imageArray addObjectsFromArray:photos];
    [self.imageArray addObjectsFromArray:photos];
    NSLog(@"%ld", self.imageArray.count);
    
    //    _collectionView.contentSize = CGSizeMake(0, ((self.imageArray.count + 2) / 3 ) * (_margin + _itemWH));
}

- (void)changePhoto
{
    
    _ImageStr = @"";
    for (NSString *str in _strArr) {
        _ImageStr = [_ImageStr stringByAppendingString:str];
//        _ImageStr = [_ImageStr stringByAppendingString:@","];
    }
    
    NSDictionary *params = @{@"msg":_ImageStr};
    
    YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:[NSString stringWithFormat:@"/User/chgAvatar.html?token=%@", token] paramDic:params RegisterApiMethod:RequestMethodPost];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.listArr = [NSMutableArray array];
        NSNumber *num = [request.responseBody objectForKey:@"result"];
        if ([num isEqualToNumber:[NSNumber numberWithInt:1]]) {
            [self getData];
        }
        NSLog(@"%@", num);
    } failure:^(YTKBaseRequest *request) {
        
    }];
}

- (void)shangchuan{
    //       上传地址
    //    NSURL *url = [NSURL URLWithString:@"http://qyjjlb.dev.hsydev.com/api.php/Public/imgsUpload.html"];
    self.mbView = [[MBProgressHUD alloc] initWithView:self.view];
    self.mbView.labelText = @"正在上传";
    [self.mbView setMode:MBProgressHUDModeIndeterminate];
    [self.mbView show:YES];
    [self.view addSubview:self.mbView];
    NSString *urlStr = @"http://qyjjlb.dev.hsydev.com/api.php/Public/imgsUpload.html";
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    
    // 数据类型data
    //    [request setPostFormat:ASIMultipartFormDataPostFormat];
    
    for (int i = 0; i < arr.count; i++) {
        [request addData:arr[i] withFileName:[NSString stringWithFormat:@"name%d.jpeg",i] andContentType:@"image/jpeg" forKey:[NSString stringWithFormat:@"namee%d",i]];
        
    }
    if (!self.queue) {
        self.queue = [[ASINetworkQueue alloc] init];
        self.queue.maxConcurrentOperationCount = 1;
    }
    [request setDelegate:self];
    
    [request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestWentWrong:)];
    [self.queue addOperation:request];
    [self.queue go];
    

}

- (void)requestDone:(ASIFormDataRequest *)request
{
    NSData *data = [request responseData];
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    _strArr = [result objectForKey:@"result"];
    [self changePhoto];
    NSLog(@"%@", data);
    [self.mbView removeFromSuperview];
    
}
- (void)requestWentWrong:(ASIFormDataRequest *)request
{
    
    
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"完成");
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSDictionary *params = @{@"msg":@"1"};
        
        YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:[NSString stringWithFormat:@"/User/chgSex.html?token=%@", token] paramDic:params RegisterApiMethod:RequestMethodPost];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            [self getData];
        } failure:^(YTKBaseRequest *request) {
            
        }];
    } else {
        NSDictionary *params = @{@"msg":@"2"};
        
        YTKNetHandle *api = [[YTKNetHandle alloc]initWithUrl:[NSString stringWithFormat:@"/User/chgSex.html?token=%@", token] paramDic:params RegisterApiMethod:RequestMethodPost];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            [self getData];
        } failure:^(YTKBaseRequest *request) {
        }];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self takePhotoOrSelectAlbum];
        } else if (indexPath.row == 1){
            ChangeNickNameViewController *changNN = [[ChangeNickNameViewController alloc] init];
            [self.navigationController pushViewController:changNN animated:YES];
        } else {
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"" message:@"修改性别" delegate:self cancelButtonTitle:nil otherButtonTitles:@"男", @"女", nil];
            [alter show];
        }
    } else if (indexPath.section == 1) {
//        ChangeCompanyNameViewController *changCN = [[ChangeCompanyNameViewController alloc] init];
//        [self.navigationController pushViewController:changCN animated:YES];
       
    } else if (indexPath.section == 2) {
//        RealNameViewController *RN = [[RealNameViewController alloc] init];
//        [self.navigationController pushViewController:RN animated:YES];
        
    } else {
        ChangePasswordViewController *changPW = [[ChangePasswordViewController alloc] init];
        [self.navigationController pushViewController:changPW animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    } else if (section == 1) {
        return 1;
    } else  if(section == 2){
        return 1;
    }
    return section;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor huiseColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  44;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    [self getData];
//    [self changePhoto];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
